package com.uade.magicCompany.dao;

import java.util.List;

import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.uade.magicCompany.entities.EntradaEntity;
import com.uade.magicCompany.entities.UsuarioEntity;

public class DAOEntradasImpl extends
		AbstractBaseGenericDAOImpl<EntradaEntity, Long> implements DAOEntrada {

	private static Logger log = Logger.getLogger(DAOEntradasImpl.class);

	@Override
	public EntradaEntity buscarEntradaPorUsuario(Long idUsuario) {
		// Get the entity manager for the tests.
		emf = Persistence.createEntityManagerFactory("JEE6Demo-Persistence");
		em = emf.createEntityManager();
		try {
			// Get a new transaction
			EntityTransaction trx = em.getTransaction();

			// Start the transaction
			trx.begin();
			// Get list
			Query query = em
					.createQuery(
							"SELECT c FROM EntradaEntity c WHERE c.usuario.id = :idUsuario").setParameter("idUsuario", idUsuario);
			List<EntradaEntity> entrada = (List<EntradaEntity>) query
					.getResultList();
			// Commit and end the transaction
			trx.commit();
			if (entrada != null && !entrada.isEmpty()) {
				return entrada.get(0);
			} else {
				log.info("No existen entradas");
				return null;
			}
		} catch (RuntimeException e) {
			// if (trx != null && trx.isActive()) {
			// trx.rollback();
			// }
			throw e;
		} finally {
			// Close the manager
			em.close();

		}

	}
}
